// pages/myself/myspellgroup/MySpellGroupDetails.js
var Zan = require('../../../dist/index');
var WxParse = require('../../../wxParse/wxParse.js');
let network = null;
let utils = null;
let api = null;
const app = getApp();
function countdown(that, endDates) {
  
  var EndTime = endDates * 1000 || [];
  var NowTime = new Date().getTime();
  var total_micro_second = EndTime - NowTime || [];
  console.log("======渲染倒计时时钟=======");
  console.log(EndTime);
  console.log(NowTime);
  console.log(total_micro_second);
  // 渲染倒计时时钟
  // that.data.endDate = dateformat(total_micro_second)
  // that.setData({
  //   clock: dateformat(total_micro_second)
  // });
  if (total_micro_second <= 0) {
    that.setData({
      total_micro_second: total_micro_second,
      endDate: "已经截止"
    })
  }else{
    that.setData({
      total_micro_second: total_micro_second,
      endDate: dateformat(total_micro_second)
    })
  }
  if (total_micro_second > 0) {
    setTimeout(function () {
      total_micro_second -= 1000;
      countdown(that, endDates);
    }, 1000)
  }

}

// 时间格式化输出，如11:03 25:19 每1s都会调用一次
function dateformat(micro_second) {
  // 总秒数
  var second = Math.floor(micro_second / 1000);
  // 天数
  var day = Math.floor(second / 3600 / 24) < 10 ? '0' + Math.floor(second / 3600 / 24) : Math.floor(second / 3600 / 24);
  // 小时
  var hr = Math.floor(second / 3600 % 24) < 10 ? '0' + Math.floor(second / 3600 % 24) : Math.floor(second / 3600 % 24);
  // 分钟
  var min = Math.floor(second / 60 % 60) < 10 ? '0' + Math.floor(second / 60 % 60) : Math.floor(second / 60 % 60);
  // 秒
  var sec = Math.floor(second % 60) < 10 ? '0' + Math.floor(second % 60) : Math.floor(second % 60);
  let date = '';
  if (day == 0) {
    date = hr + ":" + min + ":" + sec;
  } else {
    date = day + ":" + hr + ":" + min + ":" + sec;
  }
  return date;
}
Page(Object.assign({}, Zan.TopTips, Zan.Toast, {

  /**
   * 页面的初始数据
   */
  data: {
    shared: true,
    product: {},
    listSpec: [],
    showDialog: false,
    count: 0,
    radioCheckVal01: '',
    radioCheckVal02: '',
    radioCheckVal03: '',
    intelvalue01: 0,
    intelvalue02: 0,
    intelvalue03: 0,
    isClickSpecification1: 0,
    isClickSpecification2: 0,
    isClickSpecification3: 0,
    item01: '',
    item02: '',
    item03: '',
    specId: '',
    nowclock: '',
    selectedSpec: null,
    specName: '',
    RealListspec: {},
    price: 0,
    distributorId: "",
    spellGroup: null,
    spellGroupId: '',
    userid: '',
    userSpellGroupId: '',
    mobile: null,
    groupCount: 0,
    formId: '',
    groupList: [],
    iscantuan: 0,
    isSharetuan: 0,
    groupPrice: 0,
    limitCount: 0,
    storeCount: 0,
    shengyu:0,
    endDate:'',
    total_micro_second:'',
    canIUseMobile: wx.canIUse('button.open-type.getPhoneNumber')
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();

    if (app.globalData.userId) {
      bind(options);
    } else {
      // 由于 openId 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoCallback = res => {
        bind(options);
      }
    }

    wx.showShareMenu({
      withShareTicket: true //要求小程序返回分享目标信息
    })
    /**
     * 获取个人及商家信息
     */
    if (app.globalData.userAndTenantInfo) {
      this.setData({
        mobile: app.globalData.userAndTenantInfo.mobile
      })
    }

    // wx.getUserInfo({
    //   success: res => {
    //     this.setData({
    //       nickName: res.userInfo.nickName,
    //     })
    //   }
    // })
    // if (options.shared) {
    //   //存在shared表示别人分享过来的
    //   console.log('============shared==============');
    //   this.setData({
    //     sharedUserId: options.shared,
    //     isSharetuan: 1
    //   })
    // }
    this.setData({
      unigroupId: options.unigroupId,
      shengyu: options.shengyu,
      userid: app.globalData.userId,
      bananer: {
        autoplay: true,
        interval: 5000,
        duration: 300,
        indicatorDots: true,
        circular: true,
        height: utils.windowSize().winWidth / 750 * 560
      }
    })

    this.onPullDownRefresh();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    network._post_json(this, api.myGroupDetails, { unigroupId: this.data.unigroupId }, detailsSuccess);

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '花' + this.data.product.group.product.groupPrice / 100 + '元，就能拼得原价' + this.data.product.group.product.currentPrice / 100 + '元的【' + this.data.product.group.product.title + '】，太超值了',
      path: '/pages/product/SpellGroupDetails?shared=' + app.globalData.userId + '&productId=' + this.data.product.group.product.id + '&spellGroupId=' + this.data.product.groupId,
      imageUrl: this.data.product.group.product.imgUrl,
      success: function (res) {
        // 转发成功
        // if (res.shareTickets) {
        //   wx.getShareInfo({
        //     shareTicket: res.shareTickets,
        //     success: function (res) {
        //       network._post_json(this, api.updateFxcs, { directShareNums: 0, directShareQunNums: 1 }, fxcsSuccess);
        //     },
        //     fail: function (res) {
        //       // 转发失败
        //       network._post_json(this, api.updateFxcs, { directShareNums: 1, directShareQunNums: 0 }, fxcsSuccess);
        //     }
        //   })
        // } else {
        //   network._post_json(this, api.updateFxcs, { directShareNums: 1, directShareQunNums: 0 }, fxcsSuccess);
        // }

      },
      fail: function (res) {
        // 转发失败
      }
    }
  },


 


  /**
   * 如果用户已授权，并且用户昵称不为空，则直接弹框
   */
  // chooseSpan: function (e) {
  //   if (this.data.product.isVirtual == 0 && this.data.product.isActive == 1) {
  //     this.setData({
  //       showDialog: true,
  //     });
  //   } else {
  //     this.showZanTopTips('商品已下架');
  //   }
  // },
  
  chooseSpan: function (e) {
    wx.navigateTo({
      url: '/pages/product/SpellGroupDetails?spellGroupId=' + this.data.product.groupId,
    })

  },
  chooseSpan2: function (e) {
    this.showZanTopTips(this.prompt, '请先选择规格和数量！');
  },
  formSubmit: function (e) {
    this.setData({
      formId: e.detail.formId
    })
  },

  getPhoneNumber: function (e) {
    if (e.detail.encryptedData) {
      network._post_json(this, api.wxphone, { encryptedData: e.detail.encryptedData, iv: e.detail.iv, sessionKey: app.globalData.sessionKey }, bindSuccess);
    }
  },

  refresh(count) {
    this.setData({
      groupCount: this.data.groupCount - 1
    })
    if (parseInt(this.data.groupCount) <= 0) {
      this.setData({
        groupCount: 0
      })
    }

    var user = {
      avatarUrl: app.globalData.userAndTenantInfo.avatarUrl,
      nickName: app.globalData.userAndTenantInfo.nickName
    }
    this.data.spellGroup.user = user;
    this.setData({
      spellGroup: this.data.spellGroup
    })
  },
  // gotoCantuan: function (e) {
  //   console.log("// 先判断此用户是否开过或参加过此团团");
  //   var tuanitem = e.currentTarget.dataset.tuanitem;
  //   this.setData({
  //     spellGroupsId: tuanitem.spellGroupsId,
  //     sgCombId: tuanitem.sgCombId,
  //     nowclock: tuanitem.clock,
  //     userSpellGroupId: tuanitem.id,
  //     originator: tuanitem.originator
  //   })

  // },
  //查看更多
  groupMore: function (e) {
    wx.navigateTo({
      url: '/pages/product/SpellGroupMore?spellGroupsId=' + this.data.spellGroupId
    })
  }
}))


// 获取拼团详情结果
var detailsSuccess = function (that, res) {
  if (app.globalData.userId) {
    that.setData({
      userid: app.globalData.userId
    })
  } else {
    // 由于 openId 是网络请求，可能会在 Page.onLoad 之后才返回
    // 所以此处加入 callback 以防止这种情况
    app.userInfoCallback = res => {
      that.setData({
        userid: res.data.id
      })
    }
  }
  var arr = new Array();
  var listspecs = {};
  var initiallistspecs = {}
 

  if (res.data.data) {
    that.setData({
      product: res.data.data,
      endDate: res.data.data.endDate,
      // listSpec: res.data.data.spellGroupsCombs,
      // listspecs: listspecs,
      // initiallistspecs: initiallistspecs
      groupList: res.data.data.users,
      detail: res.data.data.group.product.productdetail.detail.replace(/\<img/gi, '<img style="width:100%;height:auto" ').replace(/\white-space: nowrap;/gi, '').replace(/\white-space:nowrap;/gi, '')
    })
    console.log(that.data.endDate);
    countdown(that, that.data.endDate);
    // WxParse.wxParse('details', 'html', res.data.data.group.product.productdetail.detail, that, 0);
    

    // if (that.data.product.spellGroupsCombs && !that.data.userSpellGroupId) {
    //   allPrice(that, that.data.product, that.data.listspecid);
    // }

    //此商品团长列表
    // network._post_json(that, api.getSpellGroupsDetail, { spellGroupsId: that.data.spellGroupId }, SDetailSuccess);
  }

}
// var SDetailSuccess = function (that, res) {
//   if (res.data.data) {
//     that.setData({
//       groupList: res.data.data.data,
//       allgroupList: res.data.data.data1.reverse()
//     })
//   }

// }


var bindSuccess = function (that, res) {
  if (that.data.formId && app.globalData.userAndTenantInfo.mobile != res.data.data.mobile) {
    network._post_json(that, api.sendCoupn, { formId: that.data.formId, type: 2 }, sendCoupnSuccess);
  }

  app.globalData.userAndTenantInfo.mobile = res.data.data.mobile;
  that.setData({
    mobile: res.data.data.mobile
  })
}

// var ruleSuccess = function (that, res) {
//   that.setData({
//     spellGroup: res.data.data[0],
//     // price: res.data.data.proGroupPrice,
//     groupCount: parseInt(res.data.data[0].groupSuccCount) - parseInt(res.data.data[0].groupCount)
//   })
//   if (parseInt(that.data.groupCount) <= 0) {
//     that.setData({
//       groupCount: 0
//     })
//   }
//   allPrice(that, res.data.data[0]);
// }

var fxcsSuccess = function (that, res) {
  that.showZanToast('分享成功');
}

var FSuccess = function (that, res) {
  if (res.data.data.specType1 && !res.data.data.specType2 && !res.data.data.specType2) {
    res.data.data.spellGroupsComb.specDetails = res.data.data.specType1 + ':' + res.data.data.spellGroupsComb.specDetails1
  }
  if (res.data.data.specType2) {
    res.data.data.spellGroupsComb.specDetails = res.data.data.specType1 + ':' + res.data.data.spellGroupsComb.specDetails1 + '   ' + res.data.data.specType2 + ':' + res.data.data.spellGroupsComb.specDetails2
  }
  if (res.data.data.specType3) {
    res.data.data.spellGroupsComb.specDetails = res.data.data.specType1 + ':' + res.data.data.spellGroupsComb.specDetails1 + '   ' + res.data.data.specType2 + ':' + res.data.data.spellGroupsComb.specDetails2 + '   ' + res.data.data.specType3 + ':' + res.data.data.spellGroupsComb.specDetails3
  }

  if (res.data.data) {
    that.setData({
      groupsellDetail: res.data.data,
      specDetails: res.data.data.spellGroupsComb ? res.data.data.spellGroupsComb.specDetails : '',
      cantuanlist: res.data.data.spellGroupsDetails
    })

  }
  if (that.data.nowclock != "已经截止") {
    wx.navigateTo({
      url: '/pages/product/SpellGroupDetails?spellGroupId=' + that.data.spellGroupId + '&userSpellGroupId=' + that.data.userSpellGroupId
    })
  }


}

var bind = function (options) {
  if (options.shared) {
    wx.request({
      url: api.bindUserFormQRcode,
      data: {
        openId: app.globalData.openId,
        userId: app.globalData.userId,
        tenantId: app.globalData.tenantId,
        distributorId: options.shared,
      },
      method: 'POST',
      success: function (res) {
      }
    });
  }
}

var sendCoupnSuccess = function (that, res) { }